package common;

import java.net.HttpURLConnection;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import common.WebServiceUtil.HTTP_METHOD_TYPES;

public class WebServiceInfoRequestor {

	private static String oldWebServiceURL = null;
	private static String bbanWebServiceURL = null;
	private static String ibanWebServiceURL = null;
	static {
		String propPath = FilePathHelper.getPropFilePath();
//		System.out.println("WebServiceInfoRequest: Web Service URL property path: "+propPath);
		oldWebServiceURL = PropertyHelper.getProperty(propPath,
				"oldwebserviceurl");
		bbanWebServiceURL = PropertyHelper.getProperty(propPath,
				"bbanwebserviceurl");
		ibanWebServiceURL = PropertyHelper.getProperty(propPath,
				"ibanwebserviceurl");
		
//		System.out.println("Web service urls loaded, as follow: ");
//		System.out.println(oldWebServiceURL);
//		System.out.println(bbanWebServiceURL);
//		System.out.println(ibanWebServiceURL);
	}

	private static Hashtable<String, String> headerProperties = new Hashtable<String, String>();
	static {
		headerProperties.put("X-EBAY-SOA-SERVICE-NAME", "PgwService");
		headerProperties.put("X-EBAY-SOA-OPERATION-NAME", "createCIPPrenotice");
		headerProperties.put("X-EBAY-SOA-MESSAGE-PROTOCOL", "SOAP12");
		headerProperties
				.put("X-EBAY-SOA-SECURITY-IAFTOKEN",
						"v^1.0#i^1#p^1#d^2011-12-21T22:29:12.321Z#r^0#I^2#f^0#t^H4sIAAAAAAAAAKWUT2gcVRzHM9lNJMS0REoaNYZhDFUbZua9NzvT3WFn7aybdpfuZtcmFhuU+Hb2bTJkd2aY98ZN6GXNIXjwZk/+64r/sAfBFhSkCHpQKD2UUkQFD6X14kFEKr2I+GaVdOkhFXyH32F+3+/7/X6f9+aB7ujY4Z3izp0J4YHhXhd0hwUBjoOx0ZH5fYnhR0aGwIBA6HXnusntxDvZVdsWSwVLQnWYaiBQz2CHL9SUxJJ3ktDA9yhZ9i0pBdOE6ClIENKcTCPOUxqRkkcZ9hj3AwhkYMgILQNooowJkaIhuCKJp0hIXd/jEgVI4ma75VGT4nYrsKQo9EwfU5eaHm4TajLHXLIrZZMrzSD0me/4LSmXXc3nB3x72zClJGS8npQr2ceeWcqq3M23KBR4WFgQT+FWRPbegk/EImouRY5DKJXUHN+jb6/V+qjqaY2k6qSRSR3J4KaW/v8o/vNIfRTH/LCN2d6e+IvbkJt9qUk85rKte4gcP85DsSgucumzEW65TZeElrSQt0/btZqUI3W8JbdxuEFY0MIOkR1+F6I2Cd2GqTewoaVSWE5rWJdTyNDldPNIU65Dzag72MAOwLxOsRiz6xeqVsVFn+UJ74jciwgOIOKiqlcN7SaLm+E6KEMkI7iM0CBKfiirpZJoR2zduz/4WL24yEOl0h/XknAQuI2YZ7n87zlsUktaZywwVbXT6SgdTfHDNRUBANXnK+UlZ520sbSrde8vlt1+Xw7hLuqabCvgdTf5gbPQ9dakHDI0Xed4yuUYUqUSx7hJld+zONp2bqi/4LZggm3B4D800ME8fAo8MZp4Lpl4UKQuI4qLmwp11zx+aUOibJCtALuhaWYMCIdHhbnJQ28eGngFei+C6d13YCwBxwceBTBzNzMC9x+cgAAYiFNFGYhWwON3s0k4lTzwYXT55bdnjZfev0XO7j/4ujF+VPkaTOyKBGFkKPlKF986+fuT3p0XPj9hnTh/+unHaitDX3517vCPs+cLm7kzdmPt0sVLP3386S/Wzamfbz6a7b3Xtj549eGZT0ofXfgNH0DqjdfmLlz/bHb+2kM7f33/zdXWRSV79s9MfvmN727o0/q3k86Vt6R3p1er8NyZ3uSvG2qqc/voD1O3CzP7dspfXPtj4h+GfwOBxEPGHgUAAA==");
	}

	// soap request string used for old web service and bban web service
	private static String soapRequestStr = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://www.ebay.com/marketplace/payment/v1/services\">"
			+ "<soapenv:Header/><soapenv:Body>"
			+ "<ser:createCIPPrenoticeRequest>"
			+ "<ser:extension><ser:id>12345699</ser:id><ser:version>1.0</ser:version>"
			+ "<ser:contentType>text</ser:contentType><ser:value>18</ser:value>"
			+ "</ser:extension><ser:requestHeader><ser:RequestID>1122334474</ser:RequestID>"
			+ "<ser:RequestDate>2011-11-30T11:09:27.664-07:00</ser:RequestDate>"
			+ "</ser:requestHeader>"
			+ "<ser:accountOwner>"
			+ "<ser:AccountID>"
			+ "<AccountID>" // account ID
			+ "</ser:AccountID>"
			+ "<ser:AccountSuffixID>002</ser:AccountSuffixID><ser:ClientID>20</ser:ClientID>"
			+ "</ser:accountOwner>"
			+ "<ser:merchantAccountRefID>DE_EUR_EFT_PAYMENT</ser:merchantAccountRefID>"// merchantAccountRefID>DE_EUR_EFT_PAYMENT
			+ "<ser:cipType>EFT</ser:cipType><ser:clientTransactionId>"
			+ "<clientTransactionId>" // client transaction id, will be replaced
										// by user's request parameter
			+ "</ser:clientTransactionId>"
			+ "<ser:amount currencyId=\"EUR\">"
			+ "<ser:value>"
			+ "<amount>" // amount, will be replaced by user's request parameter
			+ "</ser:value>"
			+ "</ser:amount>"
			+ "<ser:isoCountryId>DE</ser:isoCountryId>"
			+ "</ser:createCIPPrenoticeRequest>"
			+ "</soapenv:Body></soapenv:Envelope>";

	// soap request string used for iban web service
	private static String soapRequestStr_iban = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://www.ebay.com/marketplace/payment/v1/services\">"
			+ "<soapenv:Header/><soapenv:Body><ser:createCIPPrenoticeRequest>"
			+ "<ser:extension><ser:id>12345699</ser:id><ser:version>1.0</ser:version>"
			+ "<ser:contentType>text</ser:contentType><ser:value>18</ser:value>"
			+ "</ser:extension><ser:requestHeader><ser:RequestID>1122334474</ser:RequestID>"
			+ "<ser:RequestDate>2011-12-30T11:09:29.664-07:00</ser:RequestDate>"
			+ "</ser:requestHeader><ser:accountOwner><ser:AccountID>"
			+ "<AccountID>" // account ID
			+ "</ser:AccountID>"
			+ "<ser:AccountSuffixID>002</ser:AccountSuffixID><ser:ClientID>20</ser:ClientID>"
			+ "</ser:accountOwner>"
			+ "<ser:merchantAccountRefID>AT_EUR_EFT_PAYMENT</ser:merchantAccountRefID>"// merchantAccountRefID>AT_EUR_EFT_PAYMENT
			+ "<ser:cipType>EFT</ser:cipType><ser:clientTransactionId>"
			+ "<clientTransactionId>" // client transaction id, will be replaced
										// by user's request parameter
			+ "</ser:clientTransactionId>"
			+ "<ser:amount currencyId=\"EUR\"><ser:value>"
			+ "<amount>" // amount, will be replaced by user's request parameter
			+ "</ser:value></ser:amount>"
			+ "<ser:isoCountryId>DE</ser:isoCountryId></ser:createCIPPrenoticeRequest>"
			+ "</soapenv:Body></soapenv:Envelope>";

	private static String epn;
	private static String bn;
	private static String amount;
	private static String bban;
	private static String iban;
	
	/*
	 * update web service url
	 */
	public static void updateWebServiceUrl(String newOldUrl, String bbanUrl, String ibanUrl) {
		oldWebServiceURL = newOldUrl;
		bbanWebServiceURL = bbanUrl;
		ibanWebServiceURL = ibanUrl;
		
//		System.out.println("WebServiceInfoRequestor: web service url update!");
	}

	/*
	 * clear the previous epn, bn, amount, bban and iban value so that to get
	 * free from previous influence every time invoke a new web service request,
	 * should call this method first
	 */
	public static void clearValues() {
		epn = null;
		bn = null;
		amount = null;
		bban = null;
		iban = null;
	}

	public static void requestOldWebService(String accountID,
			String clientTransactionID, String amount) {
//		System.out
//				.println("WebServiceInfoRequestor.requestOldWebService: start");
//		System.out.println("WebServiceInfoRequestor: requestOldWebService: oldWebServiceURL value: " + oldWebServiceURL );

		String tempSoapRequestStr = soapRequestStr.replaceFirst("<AccountID>", accountID)
				.replaceFirst("<clientTransactionId>", clientTransactionID)
				.replaceFirst("<amount>", amount);
		HttpURLConnection conn = WebServiceUtil
				.getHttpURLConnection(oldWebServiceURL);

		headerProperties.put("Content-Length",
				String.valueOf(tempSoapRequestStr.length()));

		WebServiceUtil.setRequestHeaderProperties(conn, headerProperties);
		WebServiceUtil.setAllowInput(conn, true);
		WebServiceUtil.setAllowOutput(conn, true);
		WebServiceUtil.setHttpRequestMethodType(conn, HTTP_METHOD_TYPES.POST);

		WebServiceUtil.writeStrToConnection(tempSoapRequestStr, conn);

		String result = WebServiceUtil.getResponseAsString(conn);
		WebServiceUtil.safeClose(conn);

		// System.out.println("--------------------------------------------");
		WebServiceInfoRequestor.amount = amount;
		// System.out.println("amount: " + amount);

		String regex = "<eBayPaymentNumber>.+</eBayPaymentNumber>";
		epn = getMatchedValue(regex, result, "eBayPaymentNumber");
		// System.out.println("epn: " + epn);

		regex = "<cipReference>.+</cipReference>";
		bn = getMatchedValue(regex, result, "cipReference");
		// System.out.println("bn: " + bn);
		// System.out.println("--------------------------------------------");

		// System.out.println("WebServiceInfoRequestor.requestOldWebService: end");
	}

	public static void requestBbanWebService(String accountID,
			String clientTransactionID, String amount) {
//		System.out
//				.println("WebServiceInfoRequestor.requestBbanWebService: start");

		String tempSoapRequestStr = soapRequestStr.replaceFirst("<AccountID>", accountID)
				.replaceFirst("<clientTransactionId>", clientTransactionID)
				.replaceFirst("<amount>", amount);

//		System.out
//				.println("WebServiceInfoRequestor: be to get HttpURLConnection: "
//						+ bbanWebServiceURL);
		HttpURLConnection conn = WebServiceUtil
				.getHttpURLConnection(bbanWebServiceURL);
//		System.out
//				.println("WebServiceInfoRequestor: has get HttpURLConnection: "
//						+ bbanWebServiceURL);

		headerProperties.put("Content-Length",
				String.valueOf(tempSoapRequestStr.length()));

		WebServiceUtil.setRequestHeaderProperties(conn, headerProperties);
		WebServiceUtil.setAllowInput(conn, true);
		WebServiceUtil.setAllowOutput(conn, true);
		WebServiceUtil.setHttpRequestMethodType(conn, HTTP_METHOD_TYPES.POST);

		WebServiceUtil.writeStrToConnection(tempSoapRequestStr, conn);
		
		String result = WebServiceUtil.getResponseAsString(conn);
//		System.out.println(result);
		WebServiceUtil.safeClose(conn);

		// System.out.println("--------------------------------------------");
		WebServiceInfoRequestor.amount = amount;
		// System.out.println("amount: " + amount);

		String regex = "<eBayPaymentNumber>.+</eBayPaymentNumber>";
		epn = getMatchedValue(regex, result, "eBayPaymentNumber");
		// System.out.println("epn: " + epn);

		regex = "<cipReference>.+</cipReference>";
		bn = getMatchedValue(regex, result, "cipReference");
		// System.out.println("bn: " + bn);

		regex = "<AccountNumber>.+</AccountNumber>";
		bban = getMatchedValue(regex, result, "AccountNumber");
		// System.out.println("bban: " + bban);
		// System.out.println("--------------------------------------------");

		// System.out.println("WebServiceInfoRequestor.requestBbanWebService: end");
	}

	public static void requestIbanWebService(String accountID,
			String clientTransactionID, String amount) {
//		System.out
//				.println("WebServiceInfoRequestor.requestIbanWebService: start");

		String tempSoapRequestStr_iban = soapRequestStr_iban
				.replaceFirst("<AccountID>", accountID)
				.replaceFirst("<clientTransactionId>", clientTransactionID)
				.replaceFirst("<amount>", amount);
		HttpURLConnection conn = WebServiceUtil
				.getHttpURLConnection(ibanWebServiceURL);

		headerProperties.put("Content-Length",
				String.valueOf(tempSoapRequestStr_iban.length()));

		WebServiceUtil.setRequestHeaderProperties(conn, headerProperties);
		WebServiceUtil.setAllowInput(conn, true);
		WebServiceUtil.setAllowOutput(conn, true);
		WebServiceUtil.setHttpRequestMethodType(conn, HTTP_METHOD_TYPES.POST);

		WebServiceUtil.writeStrToConnection(tempSoapRequestStr_iban, conn);

		String result = WebServiceUtil.getResponseAsString(conn);
		WebServiceUtil.safeClose(conn);

		// System.out.println("--------------------------------------------");
		WebServiceInfoRequestor.amount = amount;
		// System.out.println("amount: " + amount);

		String regex = "<eBayPaymentNumber>.+</eBayPaymentNumber>";
		epn = getMatchedValue(regex, result, "eBayPaymentNumber");
		// System.out.println("epn: " + epn);

		regex = "<cipReference>.+</cipReference>";
		bn = getMatchedValue(regex, result, "cipReference");
		// System.out.println("bn: " + bn);

		regex = "<IBANAccountNumber>.+</IBANAccountNumber>";
		iban = getMatchedValue(regex, result, "IBANAccountNumber");
		// System.out.println("iban: " + iban);
		// System.out.println("--------------------------------------------");

		// System.out.println("WebServiceInfoRequestor.requestIbanWebService: end");
	}

	public static String getMatchedValue(String regex, String s,
			String paramName) {
		String rs = null;
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(s);
		while (m.find()) {
			rs = m.group();
			// System.out.println(rs);
			break;
		}
		if (rs != null) {
			rs = rs.substring(rs.indexOf(">") + 1,
					rs.lastIndexOf("</" + paramName + ">"));
		}

		return rs;
	}

	public static String getEpn() {
		return epn;
	}

	public static String getBn() {
		return bn;
	}

	public static String getAmount() {
		return amount;
	}

	public static String getBBan() {
		return bban;
	}

	public static String getIBan() {
		return iban;
	}

}
